package com.wpp.concurrent.util.phaserdemo;

import java.util.Random;
import java.util.concurrent.Phaser;

public class FunOfCyclicBarrier {
    public static void main(String[] args) {
        Phaser phaser = new Phaser(5);

        for (int i = 0; i < 5; i++) {
            new MyThread("线程-" + (i + 1), phaser).start();
        }

        phaser.awaitAdvance(0);
        System.out.println("运行结束");
    }
}

class MyThread extends Thread {

    private final Phaser phaser;
    private final Random random = new Random();

    public MyThread(String name, Phaser phaser) {
        super(name);
        this.phaser = phaser;
    }

    @Override
    public void run() {
        System.out.println(getName() + " - 开始向公司出发");
        slowly();
        System.out.println(getName() + " - 已经到达公司");
        // 到达同步点，等待其他线程
        phaser.arriveAndAwaitAdvance();

        System.out.println(getName() + " - 开始笔试");
        slowly();
        System.out.println(getName() + " - 笔试结束");
        // 到达同步点，等待其他线程
        phaser.arriveAndAwaitAdvance();

        System.out.println(getName() + " - 开始面试");
        slowly();
        System.out.println(getName() + " - 面试结束");
    }

    private void slowly() {
        try {
            Thread.sleep(random.nextInt(1000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}